import { Router } from "vue-router";
import NProgress from "@/utils/progress";
// import { asyncRoutes } from "./data";
import permissionStore from "@/store/modules/permission";
import baseStore from "@/store/modules/base";
import { addAsyncRouteEngineering } from "./utils";
import actions from "@/plugin/qiankun/globalState";
import { getAuthent } from "@/utils/auth";
// 判断当前权限路由是否已经初始化了
export default function InitRoute(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    document.title = `${to.meta.menuName || "加载中..."} | 方天画戟SaaS系统`;
    if (to.path !== "/login") {
      if (permissionStore.whiteList.includes(to.path)) {
        next();
      } else {
        if (window.sessionStorage.getItem("token")) {
          // 有登录信息放行
          // 根据权限获取路由  此处写死
          if (!permissionStore.asyncRoutes.length) {
            await permissionStore.getUserInfo();
            await permissionStore.initCustomConfig();
            await baseStore.initAllStaticData();
            const addRoutes = addAsyncRouteEngineering(permissionStore.asyncRoutes);
            const hasChildIndex = addRoutes.findIndex((t: any) => t.children.length || t.type === 2);
            addRoutes.forEach(route => router.addRoute("Layout", route));
            next({
              path: addRoutes[hasChildIndex].path || "/",
              replace: true
            });
          } else {
            if (!permissionStore.isReferesh) {
              await baseStore.initAllStaticData();
              const addRoutes = addAsyncRouteEngineering(permissionStore.asyncRoutes);
              const hasChildIndex = addRoutes.findIndex((t: any) => t.children.length || t.type === 2);
              addRoutes.forEach(route => router.addRoute("Layout", route));
              permissionStore.isReferesh = true;
              // 刷新页面、保持选中上一次打开的页面
              const selectedKeys = JSON.parse(getAuthent("selectedKeys") || "[]");
              if (selectedKeys.length) {
                next({
                  path: selectedKeys[0] || "/",
                  replace: true
                });
              } else {
                next({
                  path: addRoutes[hasChildIndex].path || "/",
                  replace: true
                });
              }
            } else {
              // 判断是否有权限、没权限 跳转到401页面
              if (!permissionStore.permissionMap[to.path] && !permissionStore.whiteList.includes(to.path)) {
                router.push("/401");
              } else {
                // 按需引入缓存、没有访问过的页面就不加入keepAlive列表/ 优化缓存性能
                if (to.name) {
                  if (!permissionStore.cacheList.includes(to.name as string) && to.meta.keepAlive === 1) {
                    await permissionStore.operationCache("add", to.name as string);
                    actions.setGlobalState({
                      cachePageList: permissionStore.cacheList
                    });
                  }
                }
              }
              next();
            }
          }
        } else {
          // 没有登陆 重定向到登录页
          next(`/login?redirect=${to.path}`);
        }
      }
    } else {
      // 登陆页面
      if (window.sessionStorage.getItem("token")) next("/");
      else next();
    }
  });
  router.afterEach(() => {
    NProgress.done();
  });
}
